import React, { useEffect, useState } from 'react'
import { Dropdown, Icon, Menu } from 'antd';
import cn from 'classnames';
// import { queryMapping } from '@/services/salaryManage/salaryCalculate';
import styles from './index.less';

const Editor = ({ value = [], onChange, disabled, conditionList = [] }) => {
    // 当前条件为数组，记录历史列表，方便删除时确认当前条件列表
    const [currentCondition, setCurrentCondition] = useState([null]);
    // 当前条件列表为数组，同样记录了历史条件列表
    const [currentConditionList, setCurrentConditionList] = useState([]);
    // const [mapTable, setMapTable] = useState({});
    // const getMapping = async () => {
    //     try {
    //         const { code, data = {} } = await queryMapping();
    //         if (code === 10000) {
    //             setMapTable(data.map);
    //         }
    //     } catch (e) {
    //         console.log(e);
    //     }
    // };
    const onSetValue = item => {
        const newList = value.slice();
        newList.push(item);
        onChange(newList);
    };
    const onDeleteValue = index => {
        const newList = value.slice();
        newList.splice(index, 1);
        onChange(newList);
    };
    // eslint-disable-next-line no-bitwise
    const getUUID = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    const menu = (
        <Menu>
            {(currentConditionList.length ? currentConditionList[currentConditionList.length - 1] : []).map(item => (
                <Menu.Item key={item.key}>
                    <a
                        onClick={() => {
                            const params = {
                                funcType: 'condition',
                                func: item.code,
                                funcName: item.name,
                                key: item.code
                            };
                            // 设置当前条件
                            setCurrentCondition([...currentCondition, params]);
                            onSetValue(params);
                        }}
                    >
                        {item.name}
                    </a>
                </Menu.Item>
            ))}
        </Menu>
    );

    const getCurrentDisabledStatus = (type, sign) => {
        const len = value.length;
        if (len) {
            // 获取当前输入框最后一个值
            const last = value[len - 1];
            // 最后值为前括号,可输入数字、条件
            if (last.func === '(') {
                return ['num', 'condition'].includes(type);
            }
            // 最后值为后括号，或是条件，只能输入运算符
            if (last.func === ')' || last.funcType === 'condition') {
                return ['+', '*', '/'].includes(sign);
            }

            if (last.funcType === 'condition') {
                return ['+', '*', '/', ')'].includes(sign)
            }

            // 最后值是数字，可输入运算符及括号结束符，或继续是数字
            if (last.funcType === 'num') {
                return ['+', '*', '/', ')'].includes(sign) || type === 'num';
            }
            // 最后值为运算符
            if (['+', '*', '/'].includes(last.func)) {
                // 当前存在条件，根据条件映射表查找改条件运算符下是否存在后置条件列表
                const conditions = currentCondition[currentCondition.length - 1];
                if (conditions) {
                    return ['num', 'condition'].includes(type);
                    // return mapTable[conditions.func] && mapTable[conditions.func][last.func]
                    //     ? ['num', 'condition'].includes(type)
                    //     : type === 'num';
                }
                // 当前不存在条件，可输入数字或条件
                return ['num', 'condition'].includes(type);
            }
            return false;
        }
        // 当前不存在任何值，可输入前括号、数字、条件
        return sign === '(' || ['num', 'condition'].includes(type);
    };
    useEffect(() => {
        setCurrentConditionList([conditionList]);
    }, [conditionList.length]);
    useEffect(() => {
        // getMapping();
    }, []);
    return (
        <div className={styles.editWrap}>
            <div className={styles.editHeader}>
                <ul className={styles.editOperatorList}>
                    {['+', '*', '/', '(', ')'].map(sign => (
                        <li
                            className={getCurrentDisabledStatus('sign', sign) ? styles.editOperatorItemHover : ''}
                            onClick={() => {
                                if (getCurrentDisabledStatus('sign', sign)) {
                                    // 输入），则表示当前条件置空，条件列表重新为所有条件可选项
                                    if ([')'].includes(sign)) {
                                        setCurrentCondition([...currentCondition, null]);
                                        // setCurrentConditionList([...currentConditionList, conditionList]);
                                    }
                                    // 输入运算符，判断当前是否有条件
                                    if (['+', '*', '/'].includes(sign)) {
                                        const conditions = currentCondition[currentCondition.length - 1];
                                        if (conditions) {
                                            setCurrentCondition([
                                                ...currentCondition,
                                                conditions
                                            ]);
                                            // const codeList = mapTable?.[conditions.func]?.[sign] ?? [];
                                            // const newConditionList = codeList
                                            //     ? conditionList.filter(item =>
                                            //         codeList.some(code => code === item.key)
                                            //     ) || []
                                            //     : [];

                                            // setCurrentConditionList(
                                            //     [...currentConditionList, newConditionList]
                                            // );
                                        } else {
                                            setCurrentCondition([...currentCondition, null]);
                                        }
                                    }
                                    onSetValue({ funcType: 'sign', func: sign, key: getUUID() });
                                }
                            }}
                            key={sign}
                        >
                            {sign}
                        </li>
                    ))}
                </ul>
                <div className={styles.editHeaderLine} />
                <div className={styles.editKeyboardBtn}>
                    <div
                        className={cn(styles.editTextColor, {
                            [styles.editTextColorHover]: getCurrentDisabledStatus('num')
                        })}
                        onClick={e => e.preventDefault()}
                    >
                        <span className={styles.editKeyboardBtnText}>数字</span>
                        <span className={styles.triangle} />
                        <div className={styles.editKeyboardList}>
                            <ul className={styles.editKeyboardContent}>
                                {[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '.'].map(num => (
                                    <li
                                        onClick={() => {
                                            onSetValue({
                                                funcType: 'num',
                                                func: num,
                                                key: getUUID()
                                            });
                                        }}
                                        key={num}
                                    >
                                        {num}
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                </div>
                <div className={styles.editHeaderLine} />
                <div className={styles.editKeyboardBtn}>
                    <Dropdown
                        overlay={menu}
                        placement="topCenter"
                        arrow
                        disabled={!getCurrentDisabledStatus('condition')}
                    >
                        <div
                            className={cn(styles.editTextColor, {
                                [styles.editTextColorHover]: getCurrentDisabledStatus('condition')
                            })}
                            onClick={e => e.preventDefault()}
                        >
                            <span className={styles.editKeyboardBtnText}>条件选择</span>
                            <span className={styles.triangle} />
                        </div>
                    </Dropdown>
                </div>
            </div>
            <div className={cn(styles.editContent, { [styles.editContentDisabled]: disabled })}>
                {value &&
                value.map((item, index) => (
                    <div
                        key={disabled ? index : item.key}
                        className={cn(styles.editContentItem,
                            {
                                [styles.editContentItemHover]: index === value.length - 1
                            }
                        )}
                    >
                        <span>{item.funcName || item.func}</span>
                        <Icon
                            type="close-circle"
                            theme="filled"
                            className={styles.editContentCloseIcon}
                            onClick={() => {
                                if (['+', '*', '/', ')'].includes(item.func)) {
                                    const newCurrentConditionList = currentConditionList.slice();
                                    if (newCurrentConditionList.length > 1) {
                                        newCurrentConditionList.pop();
                                        // setCurrentConditionList(newCurrentConditionList);
                                    }
                                }
                                if (item.funcType === 'condition' || ['+', '*', '/', ')'].includes(item.func)) {
                                    const newCurrentCondition = currentCondition.slice();
                                    newCurrentCondition.pop();
                                    setCurrentCondition(newCurrentCondition);
                                }
                                onDeleteValue(index);
                            }}
                        />
                    </div>
                ))}
            </div>
            {disabled ? <div style={{ position: 'absolute', width: '100%', height: '100%', left: 0, top: 0 }} /> : null}
        </div>
    );
};

export default Editor;
